<?php

namespace app\models;
use app\models\AuthItem;
use app\models\AuthAssignment;
use Yii;

/**
 * This is the model class for table "admin".
 *
 * @property string $id
 * @property string $username 用户名
 * @property string $password 密码
 * @property string $icon 头像
 * @property int $status 状态
 * @property int $created_at 创建时间
 */
class Admin extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['status', 'created_at'], 'integer'],
            [['username', 'password', 'icon'], 'string', 'max' => 255]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
      return [
        'id' => 'ID',
        'username' => 'Username',
        'password' => 'Password',
        'icon' => 'Icon',
        'status' => 'Status',
        'created_at' => 'Created At',
      ];
    }

    public function showIcon(){
      if($this->icon){
        return $this->icon;
      }
      return Yii::$app->params['logo'];
    }

    public function removeTokens(){
      UserLogin::deleteAll(
        'user_id = :user_id and token != :token',
        [':user_id'=>$this->id, ':token'=>$this->getBearToken()]
      );
    }

    private function getBearToken(){
      $authHeader = Yii::$app->getRequest()->getHeaders()->get('Authorization');
      if (preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
          return $matches[1];
      } else {
          return null;
      }
    }
}
